<?php

namespace App\Http\Controllers;

use App\Exports\ArchiveVolume10Export;
use App\Exports\ArchiveVolumeExport;
use App\Exports\LedgerEquipmentExport;
use App\Imports\ArchiveManageVolumeImport;
use App\Imports\LedgerEquipmentImport;
use App\Models\ArchiveManageVolume;
use App\Models\LedgerEquipment;
use App\Models\Menu;
use App\Models\PartCompany;
use App\Models\Project;
use App\Services\ArchiveManageService;
use App\Services\AttachmentService;
use App\Services\CommonService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class LedgerEquipmentController extends Controller
{
    /**
     * 新增数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-31 9:08
     */
    public function addData(Request $request): JsonResponse
    {
        $params    = $request->input();
        $thisQuery = LedgerEquipment::query()
            ->where('project_id', $params['project_id']);
        if (request()->filled('selectIds')) { //视为插入一行，插入到被选行的上方，然后更新当前案卷下的卷内序号
            $selectIds = to_array($params['selectIds']); //id 为一个或多个，
            $serialNo  = LedgerEquipment::query()->whereIn('id', $selectIds)->min('serial_no'); //获取选择里面的最小值
            $thisQuery->where('serial_no', '>=', $serialNo)->increment('serial_no'); //把序号大于当前的那些数据增加
        } else { //获取本案卷最大的序号再 + 1
            $info     = $thisQuery->latest('serial_no')->select('serial_no')->first();
            $serialNo = $info ? $info->serial_no + 1 : 1;
        }
        $batchData['project_id'] = $params['project_id'];
        $batchData['serial_no']  = $serialNo;
        $batchData['name']       = '这是默认物资设备名称';
        $batchData['created_at'] = now();
        $batchData['updated_at'] = now();
        LedgerEquipment::query()->insert($batchData);

        $msg = request()->filled('selectIds') ? "成功插入1条数据" : "成功新增1条数据";

        return $this->success('', $msg);
    }

    /**
     * 修改数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-31 9:09
     */
    public function updateData(Request $request): JsonResponse
    {
        $rowData = $request->input('rowData');

        $ledgerEquipment                 = LedgerEquipment::query()->find($rowData['id']);
        $ledgerEquipment->serial_no      = $rowData['serial_no'];
        $ledgerEquipment->name           = $rowData['name'];
        $ledgerEquipment->model_num      = $rowData['model_num'];
        $ledgerEquipment->remark         = $rowData['remark'];
        $ledgerEquipment->prepare_person = $rowData['prepare_person'];
        $ledgerEquipment->reviewer       = $rowData['reviewer'];
        $ledgerEquipment->record_date    = $rowData['record_date'];

        $ledgerEquipment->save();

        return $this->success('', '修改成功！');
    }

    /**
     * 获取业务规范类列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-31 9:09
     */
    public function getList(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');
        $keyword   = $request->input('keyword');
        $perPage   = $request->input('per_page') ?: 20;

        $list = LedgerEquipment::query()
            ->where('project_id', $projectId)
            ->when($keyword, function ($query) use ($keyword) {
                $likeKeyword = "%{$keyword}%";
                return $query->where('name', 'like', $likeKeyword)->orWhere('model_num', 'like', $likeKeyword);
            })
            ->orderBy('serial_no')
            ->select('*')
            ->paginate($perPage);

        $data = $list->isNotEmpty() ? $list->toArray() : [];

        return $this->success($data);
    }

    /**
     * 导入业务规范等目录
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @author: lxk
     * @date: 2024-12-31 9:07
     */
    public function import(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');

        CommonService::isFileValid($request); //验证文件是否合法
        $importCountKey = get_rand_str('import_ledger_equipment_count');
        redis()->setex($importCountKey, 600, 0); //用时最大10分钟
        Excel::import(new LedgerEquipmentImport($importCountKey, $projectId), $request->file('file'));
        $count = redis()->get($importCountKey) ?: 0;

        CommonService::addActionLog("导入物资设备台账", "【{$count}】条数据");

        return $this->success('', "成功导入【{$count}】条数据");
    }

    /**
     * 导出数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-31 9:07
     */
    public function export(Request $request): JsonResponse
    {
        $projectId   = $request->input('project_id');
        $keyword     = $request->input('keyword');
        $selectIds   = $request->input('selectIds');
        $projectName = Project::query()->where('id', $projectId)->value('title');
        try {
            $fileName = get_valid_path("{$projectName}_物资设备台账_") . date('His') . '.xlsx';
            $filePath = "public/excels/$fileName";
            (new LedgerEquipmentExport($projectId, $keyword, $selectIds))->store($filePath);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        $filePath    = str_replace('public', 'storage', $filePath);
        $downloadUrl = config('site.domain') . $filePath;
        $fileInfo    = pathinfo($downloadUrl);
        $data        = [
            'basename'     => $fileInfo['basename'],
            'download_url' => $downloadUrl
        ];
        CommonService::addActionLog("导出物资设备台账");

        return $this->success($data);
    }

    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @author: lxk
     * @date: 2024-12-31 9:07
     */
    public function destroyMore(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');
        $ids       = $request->input('ids');
        if (!LedgerEquipment::destroy(to_array($ids))) {
            return $this->error('删除失败！');
        };
        $redisKey = get_rand_str('del_ledger_equipment');
        redis()->set($redisKey, 0); //定义个临时变量
        LedgerEquipment::query()
            ->where('project_id', $projectId)
            ->select('id', 'serial_no')
            ->orderBy('serial_no')
            ->orderBy('id')
            ->chunk(100, function ($list) use ($redisKey) {
                foreach ($list as $val) {
                    redis()->incrby($redisKey, 1); //加1
                    $serialNo = redis()->get($redisKey); //获取增加后的值
                    LedgerEquipment::query()->where('id', $val->id)->update(['serial_no' => $serialNo]);
                }
            });
        redis()->del($redisKey); //用完删除
        CommonService::addActionLog("删除招投标台账", "数据ID:{$ids}");

        return $this->success('', '删除成功！');
    }


}
